package com.getword.mongodao.impl;

import com.getword.domain.User;
import com.getword.mongodao.UserOperations;
import com.getword.web.model.UserQueryCondition;
import com.mongodb.client.result.UpdateResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.security.crypto.password.PasswordEncoder;

public class UserRepositoryImpl implements UserOperations {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private PasswordEncoder passwordEncoder;


    @Override
    public UpdateResult updateUser(User user) {
        Criteria where = Criteria.where("id").is(user.getId());
        Query query = Query.query(where);
        Update update = new Update();
        if (StringUtils.isNotBlank(user.getPassword())) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            update.set("password", user.getPassword());
        }
        if (StringUtils.isNotBlank(user.getUsername())) {
            update.set("username", user.getUsername());
        }
        if (user.getSchool() != null) {
            update.set("school", user.getSchool());
        }
        if (user.getBirthday() != null) {
            update.set("birthday", user.getBirthday());
        }
        return mongoTemplate.updateFirst(query, update, User.class);
    }

    @Override
    public Page<User> findAllPage(Pageable page, UserQueryCondition condition) {
        return null;
    }
}
